<?php
class AdminController extends Forum_Controller_Action
{
    public function __construct($request, $response)
    {
        if (!Model_User::getUserId()) {
            $this->_redirect('account/login');
        }
        
        if (!Model_User::isAdmin()) {
            Forum_Message::getInstance()->addError('Недостатньо прав для цієї операції');
            $this->_redirect();
        }
        
        parent::__construct($request, $response);
        
        $this->layout->setLayout('layout_admin');
    }
    
    public function indexAction()
    {
        $this->_redirect('admin/forum');
    }
    
    public function insertAction()
    {
        $this->layout->disableLayout();
        
        $data = $this->_getParam('data');
            
        $model = strtolower($this->_getParam('model'));
        
        $redirectUrl = 'admin/' . $model;
        $autocomplete = true;
        if (isset($_SERVER['HTTP_REFERER'])) {
            $redirectUrl = $_SERVER['HTTP_REFERER'];
            $autocomplete = false;
        }
        
        if (!count($data)) {
            $this->_redirect($redirectUrl, $autocomplete);
        }
        
        Forum::getSingleton($model)->insert($data);
        
        $this->_redirect($redirectUrl, $autocomplete);
    }
    
    public function updateAction()
    {
        $this->layout->disableLayout();
        
        $data = $this->_getAllParams();
        
        $model = strtolower($this->_getParam('model'));
        
        $redirectUrl = 'admin/' . $model;
        $autocomplete = true;
        if (isset($_SERVER['HTTP_REFERER'])) {
            $redirectUrl = $_SERVER['HTTP_REFERER'];
            $autocomplete = false;
        }
        
        if (!count($data['check']) || !isset($data['row'])) {
            $this->_redirect($redirectUrl, $autocomplete);
        }
        
        if ($data['row'] == 'delete') {
            Forum::getSingleton($model)->delete(array_keys($data['check']));
            $this->_redirect($redirectUrl, $autocomplete);
        }
        
        if (!isset($data[$data['row']])) {
            $this->_redirect($redirectUrl, $autocomplete);
        }
        
        Forum::getSingleton($model)->update(
            array_keys($data['check']), 
            array("{$data['row']}" => "{$data[$data['row']]}")
        );
        
        $this->_redirect($redirectUrl, $autocomplete);
    }
    
    public function __call($method, $args)
    {
        $method = str_replace('Action', '', $method);
        
        $mode = $this->_getParam('mode');
    
        if (null === $mode) {
            $this->_redirect('admin/'.$method.'?mode=all');
        }
        
        $this->view->navigation = $method . '-' . $mode;
        $this->view->data = Forum::getSingleton($method)->getList($mode);
        
        $this->render();
    }
}